package com.zeyi.chat.utils;

import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zeyi
 */
public class AvatarUtil {
    public static final String suffix = "file:/" + System.getProperty("user.dir");

    /**
     * 选择头像
     */
    public static File chooseAvatar(Stage stage, ImageView avatar, String folder) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择头像");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("PNG", "*.png"));
        File avatarFile = fileChooser.showOpenDialog(stage);
        if (avatarFile != null) {
            Platform.runLater(() -> {
                try {
                    avatar.setImage(new Image(new FileInputStream(avatarFile), avatar.prefWidth(-1), avatar.prefHeight(-1), false, true));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            });
        }
        return avatarFile;
    }

    /**
     * 保存头像
     */
    public static String copyAvatar(File file, String folder) {
        Matcher matcher = Pattern.compile(".+(.jpg|.png|.jpeg|.gif)$").matcher(file.getName());
        matcher.find();
        String avatarPath = "/images/" + folder + "/" + UUID.randomUUID() + matcher.group(1);
        String newFilePath = System.getProperty("user.dir") + avatarPath;
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFilePath));) {
            byte[] bytes = new byte[1024];
            int byteRead = 0;
            while ((byteRead = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, byteRead);
            }
        } catch (IOException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
        return avatarPath;
    }
}
